package com.lazason.wib4android;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import weibo4andriod.Paging;
import weibo4andriod.User;
import weibo4andriod.Weibo;
import weibo4andriod.WeiboException;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.lazason.wib4android.AsyncImageLoader.ImageCallback;

public class FriendHomeActivity extends BasicActivity {
	ListView listView;
	Weibo weibo;
	String screen_name;
	MyAdapter adapter;
	List<weibo4andriod.Status> friendsTimeline = null;
	int page = 1;
	boolean isLoading = false;
	TimeLineTask timeLineTask;
	Button other_weibo;
	Paging paging;
	String userId;
	String description;
	String location;
	String big_profile;
	TextView home_username;
	TextView description_text;
	TextView location_text;
	AsyncImageLoader asyncImageLoader;
	private LayoutInflater mInflater;
	ImageView home_profile;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend);
		listView = (ListView) findViewById(android.R.id.list);
		mInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		LinearLayout header = (LinearLayout) mInflater.inflate(
				R.layout.home_header, null);
		home_username = (TextView) header.findViewById(R.id.home_username);
		description_text = (TextView) header.findViewById(R.id.description);
		location_text = (TextView) header.findViewById(R.id.location);
		other_weibo = (Button) header.findViewById(R.id.other_weibo_button);

		home_profile = (ImageView) header
				.findViewById(R.id.home_profile);

		big_profile = this.getIntent().getStringExtra("big_profile");
		asyncImageLoader = new AsyncImageLoader();
		if(big_profile!=null){
			loadProfile();
		}
		paging = new Paging();
		paging.setPage(page);
		userId = this.getIntent().getStringExtra("id");
		description = this.getIntent().getStringExtra("description");
		description_text.setText(description);
		location = this.getIntent().getStringExtra("location");
		location_text.setText(location);

		screen_name = this.getIntent().getStringExtra("screen_name");

		if (screen_name == null) {
			screen_name = this.getIntent().getData().getQueryParameter(
					"screen_name");
		}
		home_username.setText(screen_name);
		listView.addHeaderView(header);
		Log.d("FriendHomeActivity", " screen_name =" + screen_name);
		weibo = OAuthConstant.getInstance().getWeibo();
		Log.d("FriendHomeActivity",
				" weibo = OAuthConstant.getInstance().getWeibo();");
		other_weibo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View paramView) {
				// TODO Auto-generated method stub

				Intent intent = new Intent();
				intent.putExtra("userId", screen_name);
				intent.setClass(FriendHomeActivity.this, OtherWib.class);
				FriendHomeActivity.this.startActivity(intent);
			}

		});
		listView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

				if (totalItemCount != 0) {
					if (firstVisibleItem + visibleItemCount > (totalItemCount - 20)
							&& page < 101) {

						if (!isLoading) {

							isLoading = true;
							// 开线程去下载网络数据

							timeLineTask = new TimeLineTask();
							page++;
							timeLineTask.execute(page);
						}

					}

				}
			}

			@Override
			public void onScrollStateChanged(AbsListView paramAbsListView,
					int paramInt) {
				// TODO Auto-generated method stub

			}

		});

		FirstTimeLineTask task = new FirstTimeLineTask();
		Log.d("FriendHomeActivity", " FirstTimeLineTask ");
		task.execute();

	}

	private class FirstTimeLineTask extends
			AsyncTask<Void, Void, List<weibo4andriod.Status>> {

		protected List<weibo4andriod.Status> doInBackground(Void... arg) {
			if (userId != null) {
				try {

					friendsTimeline = weibo.getUserTimeline(userId);

				} catch (WeiboException we) {
					we.printStackTrace();

				} catch (Exception e) {
					e.printStackTrace();

				}
				if (friendsTimeline != null) {
					return friendsTimeline;
				}
			}
			try {
				Log.d("FriendHomeActivity", URLEncoder.encode(screen_name,
						"utf-8"));

				friendsTimeline = weibo.getUserTimeline("screen_name="
						+ URLEncoder.encode(screen_name), true);

			} catch (WeiboException we) {
				we.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();

			}
			// 用中文昵称可能取不到timeline，这时需要用id来取timeline
			if (friendsTimeline == null || friendsTimeline.size() == 0) {
				try {

					String s = java.net.URLEncoder.encode(screen_name, "utf-8");
					Log.d("FriendHomeActivity", " weibo.showUser(s,true) ");
					User user = weibo.showUser(s, true);
					Log.d("FriendHomeActivity", "user id: " + user.getId());
					Log.d("FriendHomeActivity", "user name: " + user.getName());
					userId = String.valueOf(user.getId());
					friendsTimeline = weibo.getUserTimeline(userId);

				} catch (WeiboException we) {
					we.printStackTrace();

				} catch (Exception e) {
					e.printStackTrace();

				}
			}
			return friendsTimeline;
		}

		protected void onPostExecute(List<weibo4andriod.Status> friendsTimeline) {
			MyApplication.friend = new ArrayList<Map<String, Object>>();
			if (friendsTimeline == null || friendsTimeline.size() == 0) {
				Toast.makeText(getApplicationContext(), "没有找到此微博",
						Toast.LENGTH_SHORT).show();
				FriendHomeActivity.this.finish();
				isLoading = false;
				page = 1;
				return;
			}
			Log.d("FriendHomeActivity", "friendsTimeline length:"
					+ friendsTimeline.size());
			for (weibo4andriod.Status status : friendsTimeline) {
				Map<String, Object> map = Util.status2Map(status);
				MyApplication.friend.add(map);

			}

			adapter = new MyAdapter(FriendHomeActivity.this,
					MyApplication.friend, R.layout.listitem, new String[] {
							"profile", "weibo", "username", "picture",
							"retweetedText", "retweetedThumbnailPic",
							"created_at", "comment_repost" }, new int[] {
							R.id.profile, R.id.weibo, R.id.username,
							R.id.picture, R.id.retweetedText,
							R.id.retweetedThumbnailPic, R.id.createdTime,
							R.id.comment_repost }, listView);
			listView.setAdapter(adapter);
			isLoading = false;
			page = 1;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// listView.addFooterView(layout);
		}

	}

	private class TimeLineTask extends
			AsyncTask<Integer, Void, List<weibo4andriod.Status>> {

		protected List<weibo4andriod.Status> doInBackground(Integer... page) {
			List<weibo4andriod.Status> friendsTimeline = null;
			friendsTimeline = null;

			try {

				paging.setPage(page[0]);
				if (userId != null) {

					friendsTimeline = weibo.getUserTimeline(userId, paging);
				} else if (screen_name != null) {
					friendsTimeline = weibo.getUserTimeline("screen_name="
							+ URLEncoder.encode(screen_name), paging, true);
				} else {
					friendsTimeline = weibo.getUserTimeline(paging);
				}

			} catch (WeiboException we) {
				we.printStackTrace();

			} catch (Exception e) {
				e.printStackTrace();

			}

			return friendsTimeline;
		}

		protected void onPostExecute(List<weibo4andriod.Status> friendsTimeline) {
			if (friendsTimeline == null) {
				Toast.makeText(getApplicationContext(), "没有更多的微博",
						Toast.LENGTH_SHORT).show();
				isLoading = false;
				return;
			}

			for (weibo4andriod.Status status : friendsTimeline) {
				Map<String, Object> map = Util.status2Map(status);
				MyApplication.friend.add(map);
			}

			// listView.removeFooterView(layout);

			adapter.notifyDataSetChanged();
			isLoading = false;

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			// listView.addFooterView(layout);
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (MyApplication.friend != null) {
			adapter = new MyAdapter(this, MyApplication.friend,
					R.layout.listitem, new String[] { "profile", "weibo",
							"username", "picture", "retweetedText",
							"retweetedThumbnailPic", "created_at" }, new int[] {
							R.id.profile, R.id.weibo, R.id.username,
							R.id.picture, R.id.retweetedText,
							R.id.retweetedThumbnailPic, R.id.createdTime },
					listView);
			int lastItem = listView.getFirstVisiblePosition();

			listView.setAdapter(adapter);
			listView.setSelection(lastItem);
		}
		super.onResume();
	}
    protected void loadProfile(){
    	Drawable cachedImage = asyncImageLoader.loadDrawable(this, big_profile,
				"bf" + big_profile.hashCode(), Thread.MAX_PRIORITY-2,
				new ImageCallback() {
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl, String id) {

						if (home_profile != null && imageDrawable != null) { // 防止图片url获取不到图片是，占位图片不见了的情况
							home_profile.setImageDrawable(imageDrawable);

						}
					}
				});
		
		if (cachedImage == null) {
			// holder.profile.setImageResource(R.drawable.icon);
			home_profile.setImageDrawable(null);
		} else {
			home_profile.setImageDrawable(cachedImage);
		}
    }
}
